from backend.controller.util import *
from backend.models import Performance, Argument, Service, User


def save(request):
    user_id, activity, hangar, visual_design, service = (
        format_param(request, "user_id", "activity", "hangar", "visual_design", "service"))

    if not user_id:
        return format_response(WRONG_PARAM)

    # if not (activity, hangar, visual_design, service):
    #     return format_param(WRONG_PARAM)

    try:
        user = User.objects.get(id=user_id)
    except:
        return format_response(WRONG_PARAM)

    pb_service = Service.objects.all().filter(user_id=user_id)

    if pb_service:
        pb_service = Service.objects.get(user_id=user_id)
        pb_service.activity = json.dumps(activity)
        pb_service.hangar = json.dumps(hangar)
        pb_service.visual_design = json.dumps(visual_design)
        pb_service.service = json.dumps(service)
        pb_service.save()
        return format_response(SUCCESS)

    try:
        pb_service = Service(
            user=user,
            activity=json.dumps(activity),
            hangar=json.dumps(hangar),
            visual_design=json.dumps(visual_design),
            service=json.dumps(service),
        )
        pb_service.save()
        return format_response(SUCCESS)
    except:
        return format_response(WRONG_PARAM)


def get_by_user(request):
    """
    根据成员获取绩效信息
    :param request:
    :return:
    """
    user_id = request.GET.get('user_id')
    if not user_id:
        return format_response(WRONG_PARAM)
    item = Service.objects.get(user=user_id)
    data = {
        "activity": item.activity,
        "hangar": item.hangar,
        "visual_design": item.visual_design,
        "service": item.service,
        "total": item.get_total_service()
    }
    return format_response(SUCCESS, data)
